package cn.koala.key.common.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

/**
 * @description:条形码生成工具类
 * @author 刘旭
 * @time 2018年4月18日 下午2:15:45
 * 
 */
public class BarCodeGenerator {

	private BarCodeGenerator() {
		throw new UnsupportedOperationException("Utility class can not be instantiated.");
	}

	private static String[] chars = new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };

	private static String generateCode() {
		StringBuilder shortBuffer = new StringBuilder();
		String uuid = UUID.randomUUID().toString().replace("-", "");
		for (int i = 0; i < 8; i++) {
			String str = uuid.substring(i * 4, i * 4 + 4);
			int x = Integer.parseInt(str, 16);
			shortBuffer.append(chars[x % 10]);
		}
		return shortBuffer.toString();
	}

	private static Set<String> getBarCodeRandom(int size) {
		Set<String> codeSet = new HashSet<>();
		while (codeSet.size() < size) {
			codeSet.add(generateCode());
		}
		return codeSet;
	}

	private static String getBarCodeRandom() {
		return generateCode();
	}

	private static String getDate() {
		return new SimpleDateFormat("MMdd").format(new Date());
	}

	public static Set<String> getBarCode(int size) {
		Set<String> barCodes = new HashSet<>();
		getBarCodeRandom(size).forEach(b -> {
			barCodes.add("B" + getDate() + b);
		});
		return barCodes;
	}

	public static String getBarCode() {
		return "A" + getDate() + getBarCodeRandom();
	}

}
